package com.axc.gallery2.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.axc.gallery2.R;
import com.axc.gallery2.Utils;
import com.axc.gallery2.album.AlbumListViewActivity;
import com.axc.gallery2.camera.activity.CameraResultactivity;
import com.axc.gallery2.dbhelper.AlbumInfo;
import com.axc.gallery2.dbhelper.ImageInfo;
import com.axc.gallery2.dbhelper.ImagesDBhelper;
import com.axc.gallery2.edit.EditActivity;
import com.axc.gallery2.edit.SinglePicZoom;
import com.axc.gallery2.local.SetScale;
import com.axc.gallery2.net.ApiInvoker;
import com.axc.gallery2.net.activity.NetAlbumsActivity;
import com.axc.gallery2.net.activity.UploadPhotosActivity;
import com.renren.api.connect.android.Renren;

public class GridViewActivity extends Activity {

	boolean isDelSource ;
	private AlbumInfo albumInfo;
	private int position;
	ImagesDBhelper imagesDBhelper ;

	//进度对话框
	private GalleryProgressDialog galleryProgressDialog;
	private Dialog dialog;
	public static final String TYPE_ID="GRIDVIEWACTIVITY_TYPE_ID";//加载类型，本地图库，或者存档图库
	private GridViewAdapter gridViewAdapter; 
	private GridView gridView;
	AlertDialog alertDialog ;
	private int requestCode;
	int w=0;
	protected Renren renren;
	//主题应用
	public static GridViewActivity Talbum;
	public int theme = -1;
	//长按
	private boolean isLongClick;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 主题
		Talbum = this;
		theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
				android.R.style.Theme);
		setTheme(theme);
		super.onCreate(savedInstanceState);

		// 设置不显示标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		LinearLayout line = new LinearLayout(this);
		line.setOrientation(LinearLayout.VERTICAL);
		//		RootMenu rootmenu = new RootMenu(this);
		//		rootmenu.initView();
		//		try {
		//			rootmenu.iniOnClickListener();
		//		} catch (ClassNotFoundException e) {
		//			e.printStackTrace();
		//		}
		//		line.addView(rootmenu);
		//获取视图
		View view =  LayoutInflater.from(this) 
				.inflate(R.layout.mygridview, null);
		line.addView(view);   
		setContentView(line);
		final Bundle bundle=getIntent().getExtras();
		System.out.println("bundle:"+bundle==null);
		//返回
		findViewById(R.id.gridview_back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		gridView = (GridView)findViewById(R.id.gridView);
		TextView textView =new TextView(this);
		textView.setText("没有可以显示的图片");
		gridView.setEmptyView(textView);
		w=(getWindowManager().getDefaultDisplay().getWidth()-24)/3;
		//处理对话框
		galleryProgressDialog = new GalleryProgressDialog(this) {

			@Override
			public void setRun() {
				//加载本地图库
				if(bundle==null){
					//加载图片
					albumInfo=new AlbumInfo();
					albumInfo.setAlbumItems(getColumnData());

				}
				//加载存档图库
				else{
					String path=Environment.getExternalStorageDirectory().getPath()+ "/DCIM/Gallery2/";

					albumInfo=new AlbumInfo();
					albumInfo.setAlbumItems(Utils.getPictures(path));				
				}
				gridViewAdapter= new GridViewAdapter(GridViewActivity.this, albumInfo.getAlbumItems());
				gridViewAdapter.setGridviewSize(w, w);
			}
		};

		//回发处理器
		galleryProgressDialog.handler =new Handler(){

			@Override
			public void handleMessage(Message msg) {
				galleryProgressDialog.dismiss();

				gridView.setAdapter(gridViewAdapter);
				gridView.setOnItemClickListener(new OnItemClickListener()  {



					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int _position,
							long arg3) {
						//长按后不触发
						if(isLongClick){
							isLongClick=false;
							return;
						} 
						
						//弹出菜单
						position=_position;
						if(dialog==null){
							dialog=new Dialog(GridViewActivity.this, R.style.dialog_style);
							LayoutInflater iLayoutInflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
							View view=iLayoutInflater.inflate(R.layout.gridview_dialog, null);
							OnClickListener onClickListener =new OnClickListener() {

								@Override
								public void onClick(View v) {
									//设置动画
									ScaleAnimation animation=new ScaleAnimation(0.8f, 1.1f, 0.8f, 1.1f, 80,80);
									AlphaAnimation animation2 =new AlphaAnimation(0.5f, 1);
									animation2.setDuration(1000);
									animation.setDuration(1000);
									AnimationSet animationSet; animationSet=new AnimationSet(true);
									animationSet.addAnimation(animation);
									animationSet.addAnimation(animation2);
									animationSet.setDuration(1000);
									v.setAnimation(animationSet);
									//取真实图片地址
									String path="";
									ContentResolver cr = getContentResolver();
									String[] projection = { Media._ID, Media.DATA };  
									//图片编号
									String image_id=((ImageInfo)gridViewAdapter.getItem(position)).image_id;
									if(!image_id.equals("")){
										Cursor cursor = cr.query(Media.EXTERNAL_CONTENT_URI, projection,  
												Media._ID + "=" + image_id, null, null);  
										if (cursor != null) {  
											cursor.moveToFirst();  
											path = cursor.getString(cursor.getColumnIndex(Media.DATA));  
											cursor.close();
										}
									}else {
										path=((ImageInfo)gridViewAdapter.getItem(position)).image_path;
									}

									switch (v.getId()) {
									//拍照
									case R.id.index_c:
										startActivity(new Intent(GridViewActivity.this,CameraResultactivity.class));
										break;
										//上传
									case R.id.index_u:
										renren = new Renren(NetAlbumsActivity.getApiKey(), NetAlbumsActivity.getSecretKey(), NetAlbumsActivity.getAppId(), GridViewActivity.this);
										ApiInvoker.init(renren);
										if( renren.isSessionKeyValid()){
											//上传单个文件
											//											if(false){
											//												Photo.uploadPhoto(GridViewActivity.this, renren,path );
											//											}
											//上传多个文件
											//											else{
											AlbumInfo aInfo=null;
											//单选情况下设置选中的项
											if(!gridViewAdapter.getCheckable()){
												List<ImageInfo> list =new ArrayList<ImageInfo>();
												ImageInfo imageInfo=gridViewAdapter.getList().get(position);
												list.add(imageInfo);
												 aInfo=new AlbumInfo(-1,"","",list);

											}else {
												 aInfo=new AlbumInfo(-1,"","",gridViewAdapter.getCheckItemPaths());
											}
											Intent intent =new Intent(GridViewActivity.this, UploadPhotosActivity.class);
											Bundle bundle =new Bundle();
											bundle.putSerializable(AlbumInfo.SERALIZABLEKEY, aInfo);
											intent.putExtras(bundle);
											startActivity(intent);
											//											}
										}
										else {
											new AlertDialog.Builder(GridViewActivity.this).setTitle(R.string.dialogtitle).setMessage(R.string.gridview_dialog_nologin).setNegativeButton(R.string.cancel, null)
											.setPositiveButton(R.string.gridview_dialog_login, new DialogInterface.OnClickListener() {

												@Override
												public void onClick(DialogInterface dialog, int which) {
													Intent intent =new Intent(GridViewActivity.this,NetAlbumsActivity.class);
													GridViewActivity.this.startActivity(intent);
												}
											}).create().show();
										}

										break;
										//编辑
									case R.id.index_e:
										Intent intent  = new Intent();
										intent.setClass(getBaseContext(), EditActivity.class);
										Log.w("Path", path);
										Bundle bundle=new Bundle();
										bundle.putString("pp",path);
										intent.putExtra("data", bundle);
										startActivity(intent);
										break;
										//查看
									case R.id.index_v:
										//显示相册
										Intent intent1  = new Intent();
										intent1.setClass(getBaseContext(), SinglePicZoom.class); 
										Bundle bundle1=new Bundle();
										bundle1.putString("img", path);
										intent1.putExtra("imgdata", bundle1);
										GridViewActivity.this.startActivity(intent1);
										break;
										//设置壁纸
									case R.id.index_s:
										try {
											SetScale scale  =new SetScale(getBaseContext(),BitmapFactory.decodeFile(path),getWindowManager().getDefaultDisplay());
											scale.start();
											Toast.makeText(getBaseContext(), "设置成功！", Toast.LENGTH_LONG).show();
										} catch (Exception e) {
											Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
										}	
										break;

									default:
										break;
									}
									dialog.dismiss();
								}
							};



							View index_e = view.findViewById(R.id.index_e);
							index_e.setOnClickListener(onClickListener);

							View index_u = view.findViewById(R.id.index_u);
							index_u.setOnClickListener(onClickListener);

							View index_c = view.findViewById(R.id.index_c);
							index_c.setOnClickListener(onClickListener);



							View index_s = view.findViewById(R.id.index_s);
							index_s.setOnClickListener(onClickListener);

							View index_v= view.findViewById(R.id.index_v);
							index_v.setOnClickListener(onClickListener);

							dialog.setContentView(view);
						}
						dialog.show()
						;
					}

				});

			}

		};
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {



			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				isLongClick=true;
				//改变是否可多选
				if(gridViewAdapter.getCheckable()){
					gridViewAdapter.clearCheckItems();
					gridViewAdapter.setCheckAble(false);
				}else{
					gridViewAdapter.setCheckItem(position, true);
					gridViewAdapter.setCheckAble(true);
				}

				return false;
			}
		});
		galleryProgressDialog.showGalleryProgressDialog();
		requestCode =RESULT_CANCELED;
	}

	//获取图片
	private List<ImageInfo> getColumnData() {
		ContentResolver cr = getContentResolver();
		String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID, Thumbnails.DATA };
		Cursor cur = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null);
		List<ImageInfo> list=new ArrayList<ImageInfo>();
		if (cur.moveToFirst()) {
			int image_id;
			String image_path;
			int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID);
			int dataColumn = cur.getColumnIndex(Thumbnails.DATA);

			do {

				image_id = cur.getInt(image_idColumn);
				image_path = cur.getString(dataColumn);
				ImageInfo imageInfo=new ImageInfo();
				imageInfo.image_id=image_id+"";
				imageInfo.image_path=image_path;
				list.add(imageInfo);

			} while (cur.moveToNext());
			cur.close();
		}
		return list;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		System.out.println("onKeyDownIn:"+keyCode);

		if(keyCode == KeyEvent.KEYCODE_BACK){
			System.out.println("requestCode:"+requestCode);
			Intent intent = new Intent(GridViewActivity.this,AlbumListViewActivity.class);
			GridViewActivity.this.setResult(requestCode,intent);
			/*结束本Activity*/
			GridViewActivity.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
